/*
 * @Description: listen reach bottom
 */

import { useEffect } from "react";
import debounce from 'lodash/debounce';
import { useLocation } from "react-router";

/**
 * 
 * @param f 触底执行的函数
 * @param ifStop 是否停止
 * @param id div容器
 */

export default function useReachDivBottom(id, f: Function, ifStop?: boolean) {

    const { pathname } = useLocation();

    // 执行分页的路由
    const routePaginaion = ['/list', '/systemList'];

    useEffect(() => {

        // 如果当前路径不需要执行分页，强制停止
        // if (!routePaginaion.includes(pathname)) return;
        var div = document.getElementById(id);
        const handleScroll = debounce(listenScroll, 250);
        if (div) {
            div.addEventListener('scroll', handleScroll);
        }
        return () => (div || window).removeEventListener('scroll', handleScroll);
    }, [f]);

    const listenScroll = () => {
        const preLord = 20; // 指定提前加载的距离

        if (ifStop) {
            return;
        }
        if (id) {
            const scrollHeight = document.getElementById(id)?.scrollHeight || 0;
            var scrollTop = document.getElementById(id)?.scrollTop || 0;
            var clientHeight = document.getElementById(id)?.clientHeight || 0;
            if (scrollHeight - clientHeight <= scrollTop+preLord) {
                //滚动条滚到最底部
                try {
                    f();
                } catch (err) {
                    console.log('bottom-fetch error', err);
                } finally {
                    console.log('reach bottom');
                }
            }
        }
    };
};
